package Utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    //连接数据库
    public static Connection getConnection(){
        Connection conn = null;
        try {
            InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream("JDBC.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            //配置四个基本元素
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            String url = properties.getProperty("url");
            String driverClass = properties.getProperty("driverClass");

            //连接驱动
            Class.forName(driverClass);

            //连接数据库
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    //增删改关闭资源
    public static void closeResource(Connection conn, PreparedStatement pst){
        try {
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if(pst!=null){
                pst.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


    //增删改查关闭资源
    public static void CloseResource(Connection conn, PreparedStatement pst, ResultSet rs){
        try {
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if(pst!=null){
                pst.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if(rs!=null){
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
